package com.zds.passwordbox.common.util;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

public class FileUtil {

    /**
     * 向应用专属外部存储目录写入Csv文件
     *
     * @param file 目的文件
     * @param data 要写入文件的内容
     * @return true表示写入成功，false表示写入失败
     */
    public static String writeCsvFile(File file, List<String[]> data) {
        CSVWriter csvWriter;
        try {
            FileWriter fileWriter = new FileWriter(file);
            csvWriter = new CSVWriter(fileWriter);
            csvWriter.writeAll(data);
            csvWriter.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeCsvFile(OutputStream os, List<String[]> data) {
        CSVWriter csvWriter;
        try {
            csvWriter = new CSVWriter(new OutputStreamWriter(os));
            csvWriter.writeAll(data);
            csvWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从File读取CSV文件内容
     *
     * @param file 文件
     * @return 文件内容字符串
     */
    public static List<String[]> readCsvFile(File file) {
        try {
            FileReader fileReader = new FileReader(file);
            CSVReader csvReader = new CSVReader(fileReader);
            List<String[]> dataList = csvReader.readAll();
            csvReader.close();
            return dataList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从InputStream读取CSV文件内容
     *
     * @param is csv文件输入流
     * @return 文件内容字符串，如果读取失败返回null
     */
    public static List<String[]> readCsvFile(InputStream is) {
        if (is != null) {
            try {
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader bufferedReader = new BufferedReader(isr);
                CSVReader csvReader = new CSVReader(bufferedReader);
                return csvReader.readAll();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return Collections.emptyList();
    }

}
